package gui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JMenuItem;

import gui.scheduler.*;

import util.*;

public class SysTray {

	private static MenuItem scheduleItem, prefItem, loginItem;
	private static boolean loggedIn;
	public static void login() {
		loginItem.setLabel("Logout");
		scheduleItem.setEnabled(true);
		prefItem.setEnabled(true);
		loggedIn=true;
	}

	public static void main(String[] args) throws Exception {
		CalendarInterface.initService();
		CalendarInterface.selectCalendar();
		DataBase.init();
		if(SystemTray.isSupported()) {
			final SystemTray tray = SystemTray.getSystemTray();

			Image img = ImageIO.read(new File("gui/icon.png"));
			final TrayIcon icon = new TrayIcon(img,"Tray Icon");
			PopupMenu menu = new PopupMenu();
			scheduleItem = new MenuItem("Scheduler");
			final MenuItem recipeItem = new MenuItem("Recipes");
			prefItem = new MenuItem("Preferences");
			loginItem = new MenuItem("Login");
			final MenuItem quitItem = new MenuItem("Quit");

			final IngredientGUI gui = new IngredientGUI();
			ActionListener listener = new ActionListener() {
				//private boolean loggedIn=false;
				@Override
				public void actionPerformed(ActionEvent ae) {
					switch(ae.getActionCommand().charAt(0)) {
						//icon.displayMessage("Meals have been removed", "The dates these meals " +
						//		"are scheduled for have been added to a skip list. They may be " +
						//		"removed from the skip list in the Scheduler.", TrayIcon.MessageType.INFO);
					case 'S':
						JFrame frame = new JFrame();

						frame.add(new ScheduleEditor());
						frame.pack();
						frame.setSize(650,455);
						frame.setMinimumSize(new Dimension(520,300));
						frame.setVisible(true);
						break;
					case 'R':
						gui.changeToRecipe();
						break;
					case 'P':
						gui.changeToPref();
						break;
					case 'L':
						if(loggedIn) {
							loginItem.setLabel("Login");
							scheduleItem.setEnabled(false);
							prefItem.setEnabled(false);
							loggedIn=false;
							gui.changeToLogin();
						} else {
							gui.changeToLogin();
						}
						break;
					case 'Q':
						System.exit(0);
						break;
					}
				}
			};

			menu.add(scheduleItem).addActionListener(listener);
			menu.add(recipeItem).addActionListener(listener);
			menu.add(prefItem).addActionListener(listener);

			menu.addSeparator();
			menu.add(loginItem).addActionListener(listener); // login / logout
			menu.add(quitItem).addActionListener(listener);

			scheduleItem.setEnabled(false);
			prefItem.setEnabled(false);

			icon.setPopupMenu(menu);
			try {
				tray.add(icon);
			} catch (AWTException e) {
				e.printStackTrace();
			}
			//gui.changeToLogin();

		} else {
			// Run as normal application in taskbar
		}
	}
}
